/** 1. 全局类目加载脚本 */
<template>
  <div class="editor_container">
    <div class="code-container">
      <div class="script-header">
        <a-button
          type="primary"
          :loading="updateLoading"
          @click="onUpdateScript"
          >更新脚本</a-button
        >
      </div>
      <MonacoEditor
        editorId="siteCategoryEditor"
        v-model="script_code"
        lang="python"
      />
    </div>
    <div class="result-container">
      <div class="result-header">
        <h4>执行结果</h4>
        <div class="result-header-end">
          <a-button @click="execute_result">
            <SaveOutlined />
            解析结果并存储
          </a-button>
          <a-button type="primary" @click="execute">
            <RocketOutlined />
            执行
          </a-button>
        </div>
      </div>
      <div class="script-body">
        <MonacoEditor
          editorId="siteCategoryResultEditor"
          v-model="result_code"
          @change="result_update"
          ref="siteCategoryResultEditor"
          lang="json"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineExpose } from 'vue';
import { script_execute } from '@/api/script';
import { message } from 'ant-design-vue';
import {
  set_global_category,
  get_global_config_by_key,
  update_global_config_by_key,
} from '@/utils/storage.js';

const script_id = ref(-1);
const script_code = ref('print("Hello World!")');
const script_params_json = ref('');
const updateLoading = ref(false);
const result_code = ref('[\n  {}\n]');

const execute_result = () => {
  try {
    set_global_category(JSON.parse(result_code.value));
    message.success('解析结果成功');
  } catch (err) {
    message.error('解析结果失败，请检查结果格式是否正确');
    return;
  }
};

// 执行脚本
const execute = async () => {
  if (script_id.value === -1) {
    message.error('获取脚本信息失败，请手动保存修改后的脚本再刷新页面重试');
    return;
  }
  try {
    let res = await script_execute(script_id.value);
    let format_result = JSON.stringify(JSON.parse(res.data), null, 2);
    result_code.value = format_result;
  } catch (err) {
    message.error('执行脚本时发生错误');
    console.error('execute script error ->', err);
  }
};

const reload = async () => {
  let category_result = localStorage.getItem(`global-siteCategoryResult`);
  if (category_result) {
    result_code.value = category_result;
  }
  // 获取全局页面数据
  let script = await get_global_config_by_key('GLOBAL_CATEGORY_EXTRACT');
  console.log(`output-> script`, script);
  if (script) {
    script_code.value = script.configValue;
    script_id.value = script.extraInfo;
    script_params_json.value = script.paramsJson;
  } else {
    message.error('获取全局类目脚本失败');
  }
};

const onUpdateScript = async () => {
  updateLoading.value = true;
  await update_global_config_by_key(
    'GLOBAL_CATEGORY_EXTRACT',
    script_code.value,
    script_id.value,
    script_params_json.value
  );
  updateLoading.value = false;
};

const result_update = value => {
  // console.log("value ->", value);
  result_code.value = value;
};

onMounted(() => {
  reload();
});

defineExpose({
  reload,
});
</script>

<script>
import MonacoEditor from '@/components/commons/MonacoEditor.vue';
import { Button } from 'ant-design-vue';
import { RocketOutlined, SaveOutlined } from '@ant-design/icons-vue';

export default {
  name: 'SetCategoryScript',
  components: {
    MonacoEditor,
    AButton: Button,
    RocketOutlined,
    SaveOutlined,
  },
};
</script>

<style lang="scss" scoped>
.editor_container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;

  .code-container {
    height: 100%;
    width: 52%;
    display: flex;
    flex-direction: column;
  }

  .script-header {
    height: 50px;
    display: flex;
    align-items: center;
  }

  .script-body {
    flex: 1;
    width: 100%;
    min-height: 0;
  }

  .result-container {
    width: 46%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .result-header {
      height: 50px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
    }
  }
}
</style>
